package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.Delimiter;
import com.liuqianfei.markme.rules.IAction;

import java.util.List;

/**
 * Process *this* and _that_
 * @author liuqianfei
 */
public class EmphasisPostProcessAction implements IAction
{
    // Walk through delimiter list and replace text tokens with tags
    //
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        Delimiter startDelim, endDelim;
        Token token;
        String ch;
        boolean isStrong;
        List<Delimiter> delimiters = state.getDelimiters();
        int max = state.getDelimiters().size();

        for (int i = 0; i < max; i++)
        {
            startDelim = delimiters.get(i);

            if (startDelim.marker != 0x5F/* _ */ && startDelim.marker != 0x2A/* * */)
                continue;

            // Process only opening markers
            if (startDelim.end == -1)
                continue;

            endDelim = delimiters.get(startDelim.end);

            // If the next delimiter has the same marker and is adjacent to this one,
            // merge those into one strong delimiter.
            //
            // `<em><em>whatever</em></em>` -> `<strong>whatever</strong>`
            //
            isStrong = i + 1 < max
                    && delimiters.get(i + 1).end == startDelim.end - 1
                    && delimiters.get(i + 1).token == startDelim.token + 1
                    && delimiters.get(startDelim.end - 1).token == endDelim.token - 1
                    && delimiters.get(i + 1).marker == startDelim.marker;

            //ch = String.fromCharCode(startDelim.marker);
            ch = String.valueOf(startDelim.marker);

            token         = state.getTokens().get(startDelim.token);
            token.type    = isStrong ? "strong_open" : "em_open";
            token.tag     = isStrong ? "strong" : "em";
            token.nesting = 1;
            token.markup  = isStrong ? ch + ch : ch;
            token.content = "";

            token         = state.getTokens().get(endDelim.token);
            token.type    = isStrong ? "strong_close" : "em_close";
            token.tag     = isStrong ? "strong" : "em";
            token.nesting = -1;
            token.markup  = isStrong ? ch + ch : ch;
            token.content = "";

            if (isStrong)
            {
                state.getTokens().get(delimiters.get(i + 1).token).content = "";
                state.getTokens().get(delimiters.get(startDelim.end - 1).token).content = "";
                i++;
            }
        }

        // FIXME I add it
        return true;
    }
}
